import time
import webapp2

from webapp2_extras.i18n import gettext as _

from google.appengine.api import users
from apnetmodels.basicmodels import immeuble, type_of_work
from common import functions
from wtforms.ext.appengine.db import model_form

from BaseHandler import BaseHandler

class WorkTypes(BaseHandler):
    def __init__(self, *args, **kwargs):
        super(WorkTypes, self).__init__(*args, **kwargs)
        self.au = functions.GetAPNETUser()
        if not self.au:
            self.redirect(users.create_login_url(self.request.uri))
            return
        self.fields = {
                       'syndic': _('Syndic'), 'label': _('Type of work')
                       }
    
    def get(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)

    def post(self, *args, **kwargs):
        self.get_method(self.__class__, *args, **kwargs)
    
    def op_add(self, *args, **kwargs):
        imm_id = kwargs.get('imm_id', -1)
        imm = immeuble.get_by_id(int(imm_id))
        if not imm:
            self.redirect(webapp2.uri_for('mainpage'))
            return
        
        ok_message = ''
        
        WorkTypeForm = model_form(type_of_work, exclude=['syndic'])
            
        if self.request.method == 'GET':
            form = WorkTypeForm()
        
        if self.request.method == 'POST':
            form = WorkTypeForm(self.request.POST)
            
            if form.validate():
                new_wt = type_of_work(syndic = imm.syndic, 
                                     label = form['label'].data,
                                     )
                new_wt.put()
                while not new_wt.is_saved():
                    time.sleep(2)
                
                ok_message = _('Type of work was added.')
        
        template_values = {'form': form, 'ok_message': ok_message, 'fields': self.fields}
        
        template = self.jinja2.get_template('templates/base_form.html')
        self.response.out.write(template.render(template_values))
